<template>

  <view class="game-container">
    <view class="game-header">
      <text class="theme-name">{{ themeName }}</text>
      <view class="score-info">
        <text>得分: {{ score }}</text>
        <text class="star-count">⭐ {{ stars }}</text>
        <view class="speaker-toggle" @tap="toggleSpeaker">
          <text>声音 </text>
          <image 
            :src="useSpeaker 
              ? 'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/sound.png' 
              : 'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/mute.png'"
            mode="aspectFit"
            class="speaker-icon"
          />
        </view>
      </view>
    </view>

    <view class="target-hint" v-if="currentTarget">
      <text class="hint-text">{{ getThemeLabel }}</text>
    </view>

    <view class="grid-container">
      <view 
        v-for="(item, index) in gameItems" 
        :key="index"
        class="grid-item"
        :class="{ 
          'selected': selectedIndex === index, 
          'hint': showHint && index === correctIndex,
          'wrong': wrongIndex === index
        }"
        @tap="handleItemClick(index)"
      >
        <view v-if="theme === 'colors'" class="color-block" :style="{ backgroundColor: item }"></view>
        <image v-else :src="item" mode="aspectFit" class="item-image" />
      </view>
    </view>

    <view class="game-footer">
      <button class="restart-btn" type="primary" @tap="restartGame">
        重新开始
      </button>
      <button class="back-btn" type="default" @tap="backToThemes">
        返回主题
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    // 将 THEMES 移到 data 中，确保它在生命周期开始前就存在
    const THEME_DATA = {
      colors: {
        name: '颜色',
        items: ['#FF0000', '#0000FF', '#00FF00', '#FFFF00', '#800080', '#FFA500', '#FFC0CB', '#A52A2A', '#808080'],
        labels: ['红色', '蓝色', '绿色', '黄色', '紫色', '橙色', '粉色', '棕色', '灰色']
      },
      fruits: {
        name: '水果',
        items: [
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/apple.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/banana.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/orange.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/grapes.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/strawberry.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/watermelon.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/pear.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/cherry.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/fruits/pineapple.png'
        ],
        labels: ['苹果', '香蕉', '橙子', '葡萄', '草莓', '西瓜', '梨子', '樱桃', '菠萝']
      },
      animals: {
        name: '动物',
        items: [
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/cat.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/dog.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/rabbit.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/panda.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/tiger.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/elephant.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/giraffe.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/lion.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/animals/monkey.png'
        ],
        labels: ['猫', '狗', '兔子', '熊猫', '老虎', '大象', '长颈鹿', '狮子', '猴子']
      },
      numbers: {
        name: '数字',
        items: [
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/1.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/2.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/3.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/4.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/5.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/6.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/7.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/8.png',
          'https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/numbers/9.png'
        ],
        labels: ['一', '二', '三', '四', '五', '六', '七', '八', '九']
      }
    };

    return {
      THEMES: THEME_DATA,
      theme: '',
      difficulty: 'easy',
      themeName: '',
      score: 0,
      stars: 0,
      gameItems: [],
      selectedIndex: -1,
      targetIndex: 0,
      showHint: false,
      errorCount: 0,
      timeoutTimer: null,
      wrongIndex: -1,
      correctIndex: -1,
      isPageReady: false,
      currentThemeData: null,
      initialized: false,
      useSpeaker: true
    }
  },

  computed: {
    currentTarget() {
      if (!this.currentThemeData) return null;
      return this.currentThemeData.items ? this.currentThemeData.items[this.targetIndex] : null;
    },
    
    getThemeLabel() {
      if (!this.currentThemeData) return '';
      return this.currentThemeData.labels ? this.currentThemeData.labels[this.targetIndex] || '' : '';
    }
  },

  beforeCreate() {
    // 确保在页面创建前重置所有状态
    this.initialized = false;
    this.isPageReady = false;
  },

  created() {
    // 在这里进行基础数据初始化
    this.theme = '';
    this.currentThemeData = null;

    // 设置默认的音频播放选项
    if (wx.setInnerAudioOption) {
      wx.setInnerAudioOption({
        mixWithOther: true,
        obeyMuteSwitch: false,
        speakerOn: true // 强制使用扬声器播放
      });
    }
  },

  onLoad(options) {
    console.log('onLoad with options:', options);
    
    // 初始化主题数据
    if (options && options.theme && this.THEMES[options.theme]) {
      this.theme = options.theme;
      this.currentThemeData = this.THEMES[options.theme];
      this.difficulty = options.difficulty || 'easy';
      console.log('Theme initialized:', this.theme);
    } else {
      console.log('No valid theme in options');
    }

    // 立即初始化游戏
    this.$nextTick(() => {
      this.initializeGame();
    });
  },

  onReady() {
    console.log('onReady');
    this.isPageReady = true;
  },

  onUnload() {
    console.log('onUnload');
    if (this.timeoutTimer) {
      clearTimeout(this.timeoutTimer);
    }
    this.initialized = false;
    this.isPageReady = false;
  },

  methods: {
    initializeGame() {
      console.log('Initializing game...');
      try {
        // 如果没有主题数据，尝试从事件通道获取
        if (!this.currentThemeData) {
          console.log('No theme data, trying event channel');
          const eventChannel = this.getOpenerEventChannel();
          if (eventChannel && eventChannel.on) {
            eventChannel.on('gameConfig', (data) => {
              console.log('Received game config:', data);
              if (data.theme && this.THEMES[data.theme]) {
                this.theme = data.theme;
                this.currentThemeData = this.THEMES[data.theme];
                this.difficulty = data.difficulty || 'easy';
                this.startGame();
              }
            });
          }
        } else {
          this.startGame();
        }
      } catch (error) {
        console.error('Game initialization failed:', error);
        uni.showToast({
          title: '游戏初始化失败',
          icon: 'none'
        });
        
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },

    startGame() {
      console.log('Starting game with theme:', this.theme);
      if (!this.currentThemeData) {
        console.error('Cannot start game: invalid theme');
        return;
      }

      // 设置主题名称
      this.themeName = this.currentThemeData.name || '';

      // 加载星星数
      try {
        const gameProgress = uni.getStorageSync('gameProgress');
        if (gameProgress) {
          this.stars = gameProgress.stars || 0;
        }
      } catch (error) {
        console.error('Failed to load game progress:', error);
      }

      // 初始化游戏数据
      this.initGame();

      // 标记初始化完成
      this.initialized = true;

      // 播放开始音效
      this.playSound('start');
    },

    initGame() {
      console.log('Initializing game data');
      if (!this.currentThemeData) {
        console.error('Cannot initialize game: invalid theme');
        return;
      }

      // 根据主题获取项目列表
      const items = [...this.currentThemeData.items];
      
      // 随机打乱顺序
      for (let i = items.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [items[i], items[j]] = [items[j], items[i]];
      }
      
      this.gameItems = items;
      this.score = 0;
      this.selectedIndex = -1;
      this.targetIndex = 0;
      this.errorCount = 0;
      this.showHint = false;
      this.wrongIndex = -1;
      this.correctIndex = -1;
      
      // 确保页面准备就绪后再播放语音提示
      if (this.isPageReady && this.initialized) {
        console.log('Playing initial voice prompt');
        this.$nextTick(() => {
          this.playVoicePrompt();
          this.startTimer();
        });
      } else {
        console.log('Page not ready or not initialized');
      }
    },

    startTimer() {
      if (this.timeoutTimer) {
        clearTimeout(this.timeoutTimer)
      }
      this.timeoutTimer = setTimeout(() => {
        if (!this.showHint) {
          this.showHintAnimation()
        }
      }, 10000)
    },

    handleItemClick(index) {
      if (!this.currentThemeData) return;
      
      this.selectedIndex = index;
      const correctItem = this.currentThemeData.items[this.targetIndex];
      
      if (this.gameItems[index] === correctItem) {
        // 答对了
        this.playSound('correct');
        this.score++;
        this.targetIndex++;
        
        if (this.targetIndex >= this.currentThemeData.items.length) {
          // 完成一轮游戏
          this.handleGameComplete();
        } else {
          // 继续下一个
          this.playVoicePrompt();
          this.startTimer();
        }
      } else {
        // 答错了
        this.playSound('wrong');
        this.errorCount++;
        this.wrongIndex = index;
        
        // 显示错误动画
        setTimeout(() => {
          this.wrongIndex = -1;
        }, 500);
        
        if (this.errorCount >= 5) {
          this.showHintAnimation();
        }
      }
      
      // 清除选中状态
      setTimeout(() => {
        this.selectedIndex = -1;
      }, 500);
    },

    showHintAnimation() {
      // 找到正确选项的索引
      this.correctIndex = this.gameItems.findIndex(
        item => item === this.currentThemeData.items[this.targetIndex]
      )
      this.showHint = true
      this.playSound('hint')
      
      // 2秒后隐藏提示
      setTimeout(() => {
        this.showHint = false
        this.correctIndex = -1
      }, 2000)
    },

    playSound(type) {
      if (!this.useSpeaker) return; // 如果扬声器关闭，不播放音效
      const innerAudioContext = uni.createInnerAudioContext();
      innerAudioContext.src = `https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/sounds/${type}.mp3`;
      // 设置为扬声器播放
      innerAudioContext.volume = 1;
      innerAudioContext.playbackRate = 1;
      innerAudioContext.obeyMuteSwitch = false; // 忽略系统静音开关

      // 设置音频播放模式为扬声器
      wx.setInnerAudioOption({
        mixWithOther: true,
        obeyMuteSwitch: false,
        speakerOn: this.useSpeaker // 强制使用扬声器播放
      });

      innerAudioContext.play();
    },

    playVoicePrompt() {
      console.log('Playing voice prompt');
      // 确保主题数据和标签存在
      if (!this.initialized || !this.currentThemeData || !this.currentThemeData.labels || 
          this.targetIndex >= this.currentThemeData.labels.length) {
        console.error('Invalid theme data or label index');
        return;
      }

      const label = this.currentThemeData.labels[this.targetIndex];
      if (!label) {
        console.error('Label not found');
        return;
      }

      // 显示文字提示
      const promptText = '请选择';
      const fullText = `${promptText}${label}`;
      uni.showToast({
        title: fullText,
        icon: 'none',
        duration: 2500
      });

      // 如果扬声器关闭，不播放语音
      if (!this.useSpeaker) return;
      
      // 检查 WechatSI 插件是否可用
      try {
        const plugin = requirePlugin('WechatSI');
        console.log('plugin is enable?', plugin);
        console.log('plugin is enable1111?', plugin.getTextToSpeechManager);
        if (plugin && plugin.getTextToSpeechManager) {
          this.playTTSSequence(promptText, label);
        } else {
          // 如果插件不可用，使用预录制的音频文件
          this.playVoiceUrlSequence(promptText, label);
        }
      } catch (error) {
        console.error('WechatSI plugin not available:', error);
        // 插件加载失败时使用预录制的音频文件
        this.playVoiceUrlSequence(promptText, label);
      }
    },

    // 按顺序播放TTS语音
    playTTSSequence(promptText, label) {
      // 设置音频播放模式为扬声器
      wx.setInnerAudioOption({
        mixWithOther: true,
        obeyMuteSwitch: false,
        speakerOn: this.useSpeaker // 强制使用扬声器播放
      });

      // 使用 WechatSI 插件进行语音合成
      const manager = requirePlugin('WechatSI').getTextToSpeechManager();

      manager.onStart(() => {
        console.log('TTS started');
      });

      manager.onEnd(() => {
        console.log('TTS ended');
      });

      manager.onError((err) => {
        console.error('TTS error:', err);
      });

      // 开始语音合成
      manager.speak({
        lang: 'zh_CN',
        tts: true,
        content: `${promptText}${label}`,
        success: (res) => {
          console.log('TTS success:', res);
        },
        fail: (err) => {
          console.error('TTS failed:', err);
          // 如果 TTS 失败，回退到使用预录制的音频
          this.playVoiceUrlSequence(promptText, label);
        }
      });
    },
    // 按顺序播放预录制的音频文件
    playVoiceUrlSequence(promptText, label) {
      // 设置音频播放模式为扬声器
      wx.setInnerAudioOption({
        mixWithOther: true,
        obeyMuteSwitch: false,
        speakerOn: this.useSpeaker // 强制使用扬声器播放
      });

      const playAudio = (text) => {
        return new Promise((resolve, reject) => {
          const audioContext = uni.createInnerAudioContext();
          audioContext.src = `https://zhaoqi.oss-cn-hangzhou.aliyuncs.com/wx/game/voices/${encodeURIComponent(text)}.mp3`;
          audioContext.volume = 1;
          audioContext.playbackRate = 1;
          audioContext.obeyMuteSwitch = false;
          
          audioContext.onEnded(() => {
            audioContext.destroy();
            resolve();
          });
          
          audioContext.onError((err) => {
            console.error('Audio playback failed:', err);
            audioContext.destroy();
            reject(err);
          });
          
          audioContext.play();
        });
      };

      // 按顺序播放两段语音
      playAudio(promptText)
        .then(() => new Promise(resolve => setTimeout(resolve, 300))) // 添加300ms的间隔
        .then(() => playAudio(label))
        .catch(err => {
          console.error('Voice sequence playback failed:', err);
        });
    },

    handleGameComplete() {
      // 根据难度和分数给予星星奖励
      let newStars = Math.floor(this.score / 3)
      if (this.difficulty === 'medium') {
        newStars *= 2
      } else if (this.difficulty === 'hard') {
        newStars *= 3
      }
      
      this.stars += newStars
      
      // 保存进度
      uni.setStorageSync('gameProgress', {
        stars: this.stars
      })
      
      // 播放完成音效
      this.playSound('complete')
      
      uni.showModal({
        title: '太棒了！',
        content: `获得 ${newStars} 颗星星！`,
        showCancel: false,
        success: () => {
          this.initGame()
        }
      })
    },

    restartGame() {
      this.initGame()
    },

    backToThemes() {
      uni.navigateBack()
    },

    toggleSpeaker() {
      this.useSpeaker = !this.useSpeaker;
    }
  }
}
</script>

<style lang="scss">
.game-container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .theme-name {
    font-size: 36rpx;
    font-weight: bold;
  }
  
  .score-info {
    display: flex;
    gap: 20rpx;
    font-size: 32rpx;
    align-items: center;
    
    .star-count {
      color: #FFB800;
    }

    .speaker-toggle {
      padding: 10rpx;
      
      .speaker-icon {
        width: 50rpx;
        height: 50rpx;
      }
    }
  }
}

.target-hint {
  background: #fff;
  padding: 20rpx;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .hint-text {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
  }
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin: 40rpx 0;
  aspect-ratio: 1;
}

.grid-item {
  background: #fff;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  overflow: hidden;
  
  &.selected {
    transform: scale(0.95);
  }
  
  &.hint {
    animation: blink 1s infinite;
  }
  
  &.wrong {
    animation: shake 0.5s;
    background-color: #FFE0E0;
  }
  
  .color-block {
    width: 100%;
    height: 100%;
  }
  
  .item-image {
    width: 80%;
    height: 80%;
  }
}

.game-footer {
  margin-top: auto;
  display: flex;
  gap: 20rpx;
  
  button {
    flex: 1;
  }
  
  .restart-btn {
    background-color: #007AFF;
  }
  
  .back-btn {
    background-color: #f5f5f5;
    border: 2rpx solid #ddd;
  }
}

@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.3; }
  100% { opacity: 1; }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-10rpx); }
  75% { transform: translateX(10rpx); }
}
</style> 